package logic

import (
	"context"
	"fmt"
	"vip-shop/Pkg"
	"vip-shop/cache"
	"vip-shop/model"

	"vip-shop/shoprpc/internal/svc"
	"vip-shop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *shoprpc.RegisterRequest) (*shoprpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	c, _ := cache.Rdb.Get(l.ctx, "captCha"+in.Tel).Result()
	if c != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}

	s, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Tel).Result()
	if s != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	var user model.User
	model.DB.Debug().Where("tel=?", in.Tel).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("该账号已被注册")
	}
	user = model.User{

		Tel:      in.Tel,
		Password: Pkg.Md5Str(in.Password),
	}
	model.DB.Debug().Create(&user)
	return &shoprpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
